package com.ljq.apipassenger.service.impl;

import com.ljq.apipassenger.remote.ServicePassengerUserClient;
import com.ljq.apipassenger.remote.ServiceVerificationcodeClient;
import com.ljq.apipassenger.service.VerificationCodeService;
import com.ljq.intemalcommon.constant.IdentityConstant;
import com.ljq.intemalcommon.dto.ResponseResult;
import com.ljq.intemalcommon.request.VerificationCodeDTO;
import com.ljq.intemalcommon.responese.NumberCodeResponse;
import com.ljq.intemalcommon.responese.TokenResponse;
import com.ljq.intemalcommon.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ServicePassengerUserClient servicePassengerUserClient;

    @Autowired
    private ServiceVerificationcodeClient serviceVerificationcodeClient;

    // 乘客验证码前缀
    private String verificationCodePrefix = "passenger-verification-code-";
    private String TokenPrefix = "passenger-token-";

    @Override
    public ResponseResult VerificationCode(String phone) {
        String key = getRedisKey(phone);

        if(redisTemplate.opsForValue().get(key)!=null){
            log.info("手机号:{}====>验证码还未过期！",phone);
            return ResponseResult.fail("验证码还未过期！");
        }

        //获取验证码
        ResponseResult<NumberCodeResponse> numberCode = serviceVerificationcodeClient.getNumberCode(4);
        String code = numberCode.getData().getNumberCode();

        //把验证码存入Redis并设置过期时间

        redisTemplate.opsForValue().set(key, code,2, TimeUnit.MINUTES);
        //把验证码返回给用户

        log.info("{}的验证码:{}",phone,code);
        //通过短信服务商，将对应的验证码发送到手机上，阿里短信服务

        return ResponseResult.success(code);
    }


    /**
     * 根据手机号获取Redis的key
     * @return
     */
    private String getRedisKey(String phone) {
        return verificationCodePrefix+phone;
    }

    /**
     * 根据手机号获取Redis的tokenkey
     * @return
     */
    private String getRedisTokenKey(String phone) {
        return TokenPrefix + IdentityConstant.PASSENGER_IDENTITY +"-"+phone;
    }


    /**
     *
     * @param passengerPhone 手机号
     * @param verificationCode 验证码
     * @return
     */
    @Override
    public ResponseResult checkVerificationCode(String passengerPhone, String verificationCode) {
        log.info("手机号：{}==>输入验证码：{}", passengerPhone,verificationCode);
        //判断手机号和验证码是否为空
        if (ObjectUtils.isEmpty(passengerPhone)||ObjectUtils.isEmpty(verificationCode))
            return ResponseResult.fail("手机号或验证码不能为空！");
        //根据手机号去redis读取验证码
        String key = getRedisKey(passengerPhone);
        String code = redisTemplate.opsForValue().get(key);
        //校验验证码
        if (!verificationCode.equals(code)){
            return ResponseResult.fail("验证码错误！");
        }

        //判断原来是否有用户，并进行对应的处理
        VerificationCodeDTO verificationCodeDTO = new VerificationCodeDTO();
        verificationCodeDTO.setPhone(passengerPhone);
        servicePassengerUserClient.LoginOrReg(verificationCodeDTO);

        //颁发令牌，不应该用魔法值，应该用常量
        TokenResponse token = JwtUtils.getToken(passengerPhone, IdentityConstant.PASSENGER_IDENTITY);

        //把token存入Redis中
        String tokenKey = getRedisTokenKey(passengerPhone);

        redisTemplate.opsForValue().set(tokenKey,tokenKey,30,TimeUnit.DAYS);


        //返回结果给前端
        return ResponseResult.success(token);
    }

}
